import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'

import menuData from '@/data/menuData'
import appConfig from '@/data/appConfig'

import { request } from '@/axios/index'
import { getToken } from '@/utils/auth'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true,
  },
  {
    path: '/page404',
    component: () => import('@/views/page-404'),
    hidden: true,
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [],
  },

  { path: '*', redirect: '/page404', hidden: true },
]

// 动态解析路由配置
const dynamicMenus = []
function parsMenu(menuData, target) {
  // console.log(menuData, target, targetIdx)
  menuData.forEach((item, idx) => {
    // console.log(item.redirect)
    target.push({
      path: item.path,
      name: item.name,
      component: () => import('@/views/' + item.component),
      meta: { title: item.title, icon: item.icon },
      redirect: item.redirect !== undefined ? item.redirect : '',
      children: [],
    })
    if (item.children && item.children.length > 0) {
      parsMenu(item.children, target[idx].children)
    }
  })
}
// 执行递归解析动态路由函数
parsMenu(menuData, dynamicMenus)
// console.log(dynamicMenus)
// 路由树赋值给route
routes[2].children = dynamicMenus

const router = new VueRouter({
  routes, // (缩写) 相当于 routes: routes
})

router.beforeEach((to, from, next) => {
  // 路由变化时取消当前所有非全局的pending状态的请求
  request.clearPendingPool()

  document.title = to.meta.title + '—' + appConfig.app_name

  const paToken = getToken()
  // console.log(to, from, paToken)
  if (to.path === '/login') {
    if (paToken) {
      next({ path: '/' })
    }
  } else {
    if (!paToken) {
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  }
  next()
})

export default router
